package cn.itsource.pet.service.impl;

import cn.itsource.basic.exception.BusinessException;
import cn.itsource.basic.service.IBaiduAiAuditService;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.*;
import cn.itsource.order.domain.OrderPetAcquisition;
import cn.itsource.order.mapper.OrderPetAcquisitionMapper;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.pet.domain.Pet;
import cn.itsource.pet.domain.SearchMasterMsg;
import cn.itsource.pet.domain.SearchMasterMsgAuditLog;
import cn.itsource.pet.mapper.PetMapper;
import cn.itsource.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.itsource.pet.mapper.SearchMasterMsgMapper;
import cn.itsource.pet.query.SearchMasterMsgQuery;
import cn.itsource.pet.service.ISearchMasterMsgService;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.mapper.UserMapper;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    @Transactional
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        // 获取发布信息的用户
        Logininfo logininfo = LoginContext.getLoginUser(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        // 添加寻主信息
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsgMapper.save(searchMasterMsg);
        // 百度智能审核
        Boolean Booleantext = baiduAiAuditService.textAudit(searchMasterMsg.getName() + searchMasterMsg.getTitle());
        Boolean Booleanimage = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());
        // 如果都通过
        if (Booleanimage && Booleantext){
            // 修改状态
            searchMasterMsg.setState(1);
            // 获取所有商店
            List<Shop> shops = shopMapper.loadAll();
            // 解析地址经纬度
            Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
            // 根据经纬度计算出最近的店铺
            Shop nearestShop = DistanceUtil.getNearestShop(point, shops);
            // 如果找到符合条件的店铺
            if (nearestShop != null){
                searchMasterMsg.setShopId(nearestShop.getId());
            }
            // 更新数据库
            searchMasterMsgMapper.update(searchMasterMsg);
            // 添加审核成功日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            // 添加状态
            log.setState(1);
            // 添加寻主id
            log.setMsgId(searchMasterMsg.getId());
            // 添加备注
            log.setNote("审核成功!");
            searchMasterMsgAuditLogMapper.save(log);
            if (nearestShop != null){
                // 根据店铺id获取员工
                Employee employee = employeeMapper.loadByShopId(nearestShop.getId());
                // 给员工发送短信信息
                //SmsUtils.sendSms(employee.getPhone(), "你有新订单。请去" + nearestShop.getAddress() + "接回宠物宝贝！！！");
                System.out.println("你有新订单。请去" + nearestShop.getAddress() + "接回宠物宝贝！！！");
            }
            return new AjaxResult();

        }else {
            // 审核失败添加日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setState(0);
            log.setMsgId(searchMasterMsg.getId());
            log.setNote("审核失败!");
            searchMasterMsgAuditLogMapper.save(log);
            //SmsUtils.sendSms(user.getPhone(),"你发布的寻主消息未通过审核，请修改之后重新发布!!!");
            System.out.println("你发布的寻主消息未通过审核，请修改之后重新发布!!!");
            return AjaxResult.me().setSuccess(false).setMsg("审核失败");
        }

    }

    @Override
    public PageList<SearchMasterMsg> userSearchMasterMsg(SearchMasterMsgQuery query, HttpServletRequest request) {
        // 获取登录信息
        Logininfo logininfo = LoginContext.getLoginUser(request);
        // 根据LogininfoId查询用户
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        // 将userId设置进query
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        // 获取登录信息
        Logininfo logininfo = LoginContext.getLoginUser(request);
        // 根据LogininfoId查询员工
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        // 如果员工有shopId，说明是店铺管理员
        if (employee.getShopId() != null){
            query.setShopId(employee.getShopId());
        }
        return super.queryPage(query);
    }

    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    @Override
    public void accept(Map<String, Object> params) {
        Long msgId = Long.valueOf(params.get("msgId").toString());
        //1.校验改寻主消息是否已经在处理，报错
        OrderPetAcquisition orderTmp = orderPetAcquisitionMapper.loadByMsgId(msgId);
        if (orderTmp!=null){
            throw new BusinessException("已经被接单，正在处理中！");
        }

        //处理人id
        Long handlerId = Long.valueOf(params.get("handler").toString());
        String note = params.get("note").toString();
        Employee handler = employeeMapper.loadById(handlerId);

        //1 创建寻主消息所对应宠物信息
        //1.1 获取寻主消息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);
        //1.2 创建宠物信息
        Pet pet = searchMasterMsg2Pet(searchMasterMsg);
        petMapper.save(pet);

        //2 创建宠物收购订单
        OrderPetAcquisition order = buildPetAcquisitionOrder(searchMasterMsg,handler,pet);
        orderPetAcquisitionMapper.save(order);

        //3 发送消息给对应的工作人员
        System.out.println(handler.getEmail()+"-->邮件通知：您有新的"+order.getOrderSn()+"订单要处理！");
        //System.out.println(handler.getPhone()+"-->短信通知：您有新的"+order.getOrderSn()+"订单要处理！");
        // 五.发送延迟消息，若两天后店铺还未确认订单，收到宠物，就取消订单
        // 生成信息,将订单号发送出去
        Message<String> message = MessageBuilder.withPayload(order.getOrderSn()).build();
        // 1.topic 2.消息 3.消息发送超时时间 4.延时等级
        rocketMQTemplate.syncSend("pet_delay_topic",message,1000,18);
        System.out.println("已发送延迟消息!");
    }

    private OrderPetAcquisition buildPetAcquisitionOrder(SearchMasterMsg searchMasterMsg, Employee handler,Pet pet) {

        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(handler.getId());
        order.setOrderSn(orderSn);
        order.setDigest(searchMasterMsg.getName()+"的收购订单");
        //最后收购是当前时间+2两天
        long lastcomfirmtimeLong = System.currentTimeMillis()+1000*60*60*24*2;
        order.setLastcomfirmtime(new Date(lastcomfirmtimeLong));
        order.setState(0);
        order.setPrice(searchMasterMsg.getPrice());
        //        order.setPaytype(); //现金支付
        order.setPetId(pet.getId());
        order.setUserId(searchMasterMsg.getUserId());
        order.setShopId(pet.getShopId());
        order.setAddress(searchMasterMsg.getAddress());
        order.setEmpId(handler.getId());
        order.setSearchMasterMsgId(searchMasterMsg.getId());
        return order;
    }

    private Pet searchMasterMsg2Pet(SearchMasterMsg searchMasterMsg) {
        Pet pet = new Pet();
        pet.setName(searchMasterMsg.getName());
        pet.setResources(searchMasterMsg.getResources());
        pet.setTypeId(searchMasterMsg.getPetType());
        //就要获取处理人的店铺id
        pet.setShopId(searchMasterMsg.getShopId());
        pet.setUserId(searchMasterMsg.getUserId());
        pet.setSearchMasterMsgId(searchMasterMsg.getId());
        //用户发布时需要的价格 收购回来就是成本价
        pet.setCostprice(searchMasterMsg.getPrice());
        return pet;
    }


}
